import sys #for system call, open/save to file
import os
import datetime
import xmlrpclib #for accessing FiberComb server
import time #for sleeping and timing
now=datetime.datetime.now()
fdname=now.strftime("%Y-%m-%d")
rootpath='C:\\Users\\FClab\\Rb_DFCS_Data\\'+fdname
flname=raw_input("Enter file name .dat extension : ")
if not os.path.exists(rootpath):
    os.makedirs(rootpath)
path=rootpath+'\\'+flname
fn=open(path,'a')
#Input
#server_ip=raw_input("Enter IP address: ")
server_ip='134.154.249.247'
server_url='http://comb:system@'+server_ip+':8123/RPC2'
#Enter scanning range "-" for decrease
scan_range=raw_input("Enter DDS Freq scanning range (Hz): ")
#convert string to float
sr=float(scan_range)
###############################################################
# Create an object to represent our server.
server = xmlrpclib.ServerProxy(server_url);
###############################################################
#Check whether the server is alive
status=server.hello()
print status
###############################################################
#Check current DDS frequency
ddsfreq = server.comb.reprate.synth.getFreq()
print "Synthesizer is (Hz):", ddsfreq

###############################################################
#Scanning routine

#Data Channels
cDataChannels=['offset.freq','reprate.freq','aux0']
#Determine scanning direction and set target DDS frequency 
if sr > 0:
	st=1; #scan step
	tddsfreq=ddsfreq+sr #set target DDS freq
elif sr < 0:
	st=-1;
	tddsfreq=ddsfreq+sr
###############################################################

while (ddsfreq != tddsfreq):
	#set dds frequency a.k.a rep rate
	server.comb.reprate.synth.setFreq(ddsfreq+st)
	print "\n Set DDS to:", ddsfreq+st
	#sleep for 5 seconds for reprate to stabilize
	print "\n Now sleeping ...";
	time.sleep(6)
	#get latest timestamp
	#timestamp=server.data.last_timestamp()
	#query data names from cDataChannels
	print "\n Getting data..."
	data=server.data.query(-1.00000,cDataChannels)
	
	if (type(data)!=type('str')):
		timestamps=data.keys()
		timestamps.sort()
		for key, value in data.iteritems():
                        temp=value
                        for key, value in temp.iteritems():
                                fn.write(' %s \t'%(repr(value)))
		
        fn.write('\n')
        fn.close
	data='' #clean data 
	#update new dds frequency
	ddsfreq=server.comb.reprate.synth.getFreq()
	
		
